package run.iget.framework.common.handler;

import javax.annotation.Resource;

import org.springframework.context.annotation.Import;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import run.iget.framework.common.enums.BaseResultEnum;
import run.iget.framework.common.exception.BusinessException;
import run.iget.framework.common.propertity.GlobalExceptionProperties;
import run.iget.framework.common.resp.ResultResp;

/**
 * 代码千万行，注释第一行，注释不规范，迭代两行泪
 * ---------------类描述-----------------
 * 全局异常处理，统一进行保证返回给前端
 * ---------------类描述-----------------
 *
 * @author 大周
 * @date 2022/11/11 21:52
 */
@Setter
@Slf4j
@Import(GlobalExceptionProperties.class)
@RestControllerAdvice
public class GlobalExceptionHandler {

    @Resource
    private GlobalExceptionProperties globalExceptionProperties;

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResultResp<String> handleException(BusinessException ex) {
        BaseResultEnum resultEnum = ex.getResultEnum();
        consoleErrorMsg(ex);
        return ResultResp.error(resultEnum.getCode(), resultEnum.getDesc());
    }

    /**
     * SpringMVC参数绑定，Validator校验不正确
     */
    @ExceptionHandler(BindException.class)
    public ResultResp<String> bindException(BindException ex) {
        FieldError fieldError = ex.getFieldError();
        assert fieldError != null;
        consoleErrorMsg(ex);
        return ResultResp.error(BaseResultEnum.ERROR_PARAM.getCode(), fieldError.getDefaultMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResultResp<String> handleException(Exception ex) {
        consoleErrorMsg(ex);
        String simpleName = ex.getClass().getSimpleName();
        String msg = ex.getMessage();
        if (CollectionUtil.isNotEmpty(globalExceptionProperties.getExceptionClassMsg())) {
            msg = globalExceptionProperties.getExceptionClassMsg().get(simpleName);
        }
        return ResultResp.error(StrUtil.isNotBlank(msg) ? msg : ex.getMessage());
    }

    /**
     * 输出异常信息
     * @param ex
     */
    private void consoleErrorMsg(Exception ex) {
        if (!Boolean.TRUE.equals(globalExceptionProperties.getConsoleError()) || !log.isErrorEnabled()) {
            return;
        }
        log.error(ex.getMessage(), ex);
    }

}
